package com.uxsino.simo.indicator.retractor;

import com.uxsino.commons.utils.config.ConfigProp;

public class FixedWidthListRetractor extends TextListRetractor {

    private int[] column_widthes;

    @ConfigProp(name = "column_widthes", required = true)
    public void setColumnWidthes(String widthes) {
        String ws[] = widthes.split(",");

        int[] iws = new int[ws.length];

        try {
            for (int i = 0; i < ws.length; i++) {
                iws[i] = Integer.parseInt(ws[i]);
            }
            column_widthes = iws;
        } catch (NumberFormatException e) {
            throw new IllegalArgumentException("a list of number expected: " + widthes);
        }
    }

    @Override
    protected String[] splitRow(String row) {
        if (column_widthes == null || row == null || row.trim().length() == 0) {
            return null;
        }
        String[] buf = new String[column_widthes.length];
        int at = 0;
        int left = row.length();
        int column_count = 0;
        while (column_count < column_widthes.length && left > 0) {
            int w = column_widthes[column_count];
            if (w > left)
                w = left;
            buf[column_count] = row.substring(at, at + w);
            at = at + w;
            left = left - w;
            column_count++;
        }
        return buf;
    }

}
